package com.example.springbootshiro.service.impl;

import com.example.springbootshiro.dao.PermissionDao;
import com.example.springbootshiro.model.Permission;
import com.example.springbootshiro.service.PermissionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * Created by YangGang on 2021/12/16 11:33。
 */
@Service
public class PermissionServiceImpl implements PermissionService {
    private Map<String, String> permissionMapCache = null;
    @Autowired
    PermissionDao permissionDao;

    /**
     * 获取缓存的权限列表对象，如果对表`sys_permission`进行了更新操作，需要更新缓存
     * <p>
     * key：权限请求的 >>> permission_url
     * value：权限标签 >>> permission_tag
     *
     * @return
     */
    @Override
    public Map<String, String> findPermissionMapCache() {
        if (this.permissionMapCache != null) return this.permissionMapCache;
        System.out.println("findPermissionMapCache >>>");
        List<Permission> list = permissionDao.list();
        this.permissionMapCache = list.stream()
                .collect(Collectors.toMap(Permission::getPermissionUrl, Permission::getPermissionTag));
        return this.permissionMapCache;
    }


    /**
     * 添加权限，成功执行该方法后需要更新 permissionMapCache 缓存数据
     *
     * @param permission
     * @return
     */
    @Override
    public int addPermission(Permission permission) {
        permission.setPermissionId(null);
        return permissionDao.insertSelective(permission);
    }


}
